package com.hube.platform.tenant.controller;

import com.hube.platform.tenant.annotation.AutoSwitchDB;
import com.hube.platform.tenant.configuration.DynamicDataSource;
import com.hube.platform.tenant.configuration.response.Response;
import com.hube.platform.tenant.constant.AppConstant;
import com.hube.platform.tenant.entity.dto.TenantDataBaseConfigDTO;
import com.hube.platform.tenant.entity.po.TenantDataBaseConfigPO;
import com.hube.platform.tenant.entity.vo.DatabaseMonitorVO;
import com.hube.platform.tenant.helper.ApplicationContextHelper;
import com.hube.platform.tenant.helper.HikariCPHelper;
import com.hube.platform.tenant.service.TenantInfoService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author : Aaron
 * @date : 2022/6/2
 */
@Api("多租户管理")
@RestController
@RequestMapping("/tenant/manage")
public class TenantManageController {
    @Autowired
    private TenantInfoService infoService;

    @ApiOperation("测试数据源切换")
    @AutoSwitchDB
    @GetMapping("/test")
    public Response<List<TenantDataBaseConfigPO>> test() {
        List<TenantDataBaseConfigPO> result = infoService.getBaseInfoList();
        return Response.ok(result);
    }

    @ApiOperation("创建租户")
    @PostMapping("/create")
    public Response create(@RequestBody TenantDataBaseConfigDTO dto) {
        infoService.createTenant(dto);
        return Response.ok();
    }

    @ApiOperation("销毁数据源")
    @DeleteMapping("/datasource/{key}")
    public Response removeDatasource(@PathVariable("key") String key) {
        DynamicDataSource dynamicDataSource =
                (DynamicDataSource) ApplicationContextHelper.getBean(AppConstant.DYNAMIC_DATA_SOURCE);
        dynamicDataSource.deleteDataSource(key);
        return Response.ok();
    }

    @ApiOperation("更新数据源配置")
    @PutMapping("/datasource/{id}")
    public Response reloadDatasource(@PathVariable("id") String id, @RequestBody TenantDataBaseConfigDTO dto) {
        infoService.reloadDatasource(id, dto);
        return Response.ok();
    }

    @ApiOperation("多数据源监控")
    @GetMapping("/datasource/monitor")
    public Response<List<DatabaseMonitorVO>> DataSourceMonitor() {
        return Response.ok(HikariCPHelper.monitor());
    }
}
